const path = require("path");
const express = require("express");
const app = express();

const port = 3000;
let count = 1;

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.get("/chat", (req, res) => {
  const mess = "中国欢迎您";
  let turn = 0;
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
    "access-control-allow-origin": "*",
  });
  let timer = setInterval(() => {
    res.write(`data: ${mess[turn]}\n\n`);
    turn++;
    if (turn === 5) {
      clearInterval(timer);
      res.end();
    }
  }, 1000);

  req.connection.addListener(
    "close",
    () => {
      console.log("SSE connection closed!", " +", count++);
    },
    false
  );
});

app.get("/jsonp", (req, res) => {
  const data = {
    item: "fruit",
    price: 100,
  };
  const callback = req.query.callback;
  res.send(`${callback}(${JSON.stringify(data)});`);
});

app.post("/", (req, res) => {
  res.send("Got a POST request");
});

app.put("/user", (req, res) => {
  res.send("Got a PUT request at /user");
});

app.delete("/user", (req, res) => {
  res.send("Got a DELETE request at /user");
});


const my_sleep = (req, res, next) => {
  let t = req?.query?.sleep;
  if (t) {
    setTimeout(() => {
      next();
    }, t * 1000);
  } else {
    next();
  }
};

app.use(my_sleep);
app.use(express.static("public"));


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
